package com.benyanyi.loglib

import android.util.Log
import java.io.StringReader
import java.io.StringWriter
import java.lang.Exception
import javax.xml.transform.OutputKeys
import javax.xml.transform.Source
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

/**
 * @author myLove
 * @time 2017/10/31 10:44
 * @e-mail ben@yanyi.red
 * @overview
 */
internal object XmlLog {
    fun printXml(tag: String, xml: String?, headString: String) {
        var msg = xml
        if (msg != null) {
            msg = formatXML(msg)
            msg = """
                $headString
                $msg
                """.trimIndent()
        } else {
            msg = headString + Jlog.mConfig.nullTip
        }
        LogUtil.printLine(tag, true)
        val lines = msg.split(Jlog.LINE_SEPARATOR!!.toRegex()).toTypedArray()
        for (line in lines) {
            if (!LogUtil.isEmpty(line)) {
                Log.d(tag, "║ $line")
                if (!Jlog.mConfig.isWrite) {
                    return
                }
                if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
                    return
                }
                BaseLog.writeLog(tag, "║ $line")
            }
        }
        LogUtil.printLine(tag, false)
    }

    private fun formatXML(inputXML: String): String {
        return try {
            val xmlInput: Source = StreamSource(StringReader(inputXML))
            val xmlOutput = StreamResult(StringWriter())
            val transformer = TransformerFactory.newInstance().newTransformer()
            transformer.setOutputProperty(OutputKeys.INDENT, "yes")
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
            transformer.transform(xmlInput, xmlOutput)
            xmlOutput.writer.toString().replaceFirst(">".toRegex(), ">\n")
        } catch (e: Exception) {
            e.printStackTrace()
            inputXML
        }
    }
}